import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Search, Terminal, File, Settings, Zap, Globe, Clock, Star } from 'lucide-react'

interface Command {
  id: string
  title: string
  description?: string
  icon?: React.ReactNode
  shortcut?: string
  category: 'file' | 'edit' | 'view' | 'ai' | 'tools' | 'settings'
  action: () => void
}

interface CommandPaletteProps {
  isOpen: boolean
  onClose: () => void
  commands?: Command[]
}

const CommandPalette: React.FC<CommandPaletteProps> = ({
  isOpen,
  onClose,
  commands = []
}) => {
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedIndex, setSelectedIndex] = useState(0)
  const [recentCommands, setRecentCommands] = useState<string[]>([])
  const inputRef = useRef<HTMLInputElement>(null)

  // Default commands
  const defaultCommands: Command[] = [
    // File operations
    {
      id: 'file:new',
      title: 'New File',
      description: 'Create a new markdown document',
      icon: <File className="w-4 h-4" />,
      shortcut: 'Cmd+N',
      category: 'file',
      action: () => {
        window.electronAPI.showOpenDialog() // This should trigger new file
      }
    },
    {
      id: 'file:open',
      title: 'Open File',
      description: 'Open an existing markdown file',
      icon: <File className="w-4 h-4" />,
      shortcut: 'Cmd+O',
      category: 'file',
      action: () => {
        window.electronAPI.showOpenDialog()
      }
    },
    {
      id: 'file:save',
      title: 'Save File',
      description: 'Save the current file',
      icon: <File className="w-4 h-4" />,
      shortcut: 'Cmd+S',
      category: 'file',
      action: () => {
        // Trigger save
        window.dispatchEvent(new Event('file:save'))
      }
    },
    {
      id: 'file:export',
      title: 'Export Document',
      description: 'Export to PDF, HTML, or other formats',
      icon: <Globe className="w-4 h-4" />,
      category: 'file',
      action: () => {
        // Show export dialog
        window.dispatchEvent(new CustomEvent('show:export-dialog'))
      }
    },

    // AI operations
    {
      id: 'ai:polish',
      title: 'Polish Text',
      description: 'Improve writing and fix grammar',
      icon: <Zap className="w-4 h-4" />,
      shortcut: 'Cmd+Shift+P',
      category: 'ai',
      action: () => {
        const selection = window.getSelection()
        if (selection && selection.toString().trim()) {
          // Trigger AI polish
          window.dispatchEvent(new CustomEvent('ai:polish', {
            detail: { text: selection.toString() }
          }))
        }
      }
    },
    {
      id: 'ai:continue',
      title: 'Continue Writing',
      description: 'AI-powered text continuation',
      icon: <Zap className="w-4 h-4" />,
      shortcut: 'Cmd+J',
      category: 'ai',
      action: () => {
        // Trigger AI continue writing
        window.dispatchEvent(new Event('ai:continue'))
      }
    },
    {
      id: 'ai:translate',
      title: 'Translate Text',
      description: 'Translate selected text to another language',
      icon: <Globe className="w-4 h-4" />,
      shortcut: 'Cmd+Shift+T',
      category: 'ai',
      action: () => {
        const selection = window.getSelection()
        if (selection && selection.toString().trim()) {
          // Show translate dialog
          window.dispatchEvent(new CustomEvent('ai:translate', {
            detail: { text: selection.toString() }
          }))
        }
      }
    },

    // View operations
    {
      id: 'view:toggle-sidebar',
      title: 'Toggle Sidebar',
      description: 'Show or hide the file sidebar',
      icon: <Settings className="w-4 h-4" />,
      shortcut: 'Cmd+B',
      category: 'view',
      action: () => {
        window.dispatchEvent(new Event('view:toggle-sidebar'))
      }
    },
    {
      id: 'view:toggle-theme',
      title: 'Toggle Theme',
      description: 'Switch between light and dark theme',
      icon: <Settings className="w-4 h-4" />,
      shortcut: 'Cmd+Shift+D',
      category: 'view',
      action: () => {
        window.dispatchEvent(new Event('view:toggle-theme'))
      }
    },
    {
      id: 'view:focus-mode',
      title: 'Focus Mode',
      description: 'Enter distraction-free writing mode',
      icon: <Terminal className="w-4 h-4" />,
      shortcut: 'Cmd+Shift+F',
      category: 'view',
      action: () => {
        window.dispatchEvent(new Event('view:focus-mode'))
      }
    },

    // Tools
    {
      id: 'tools:word-count',
      title: 'Word Count',
      description: 'Show document word count and statistics',
      icon: <Terminal className="w-4 h-4" />,
      category: 'tools',
      action: () => {
        window.dispatchEvent(new Event('tools:word-count'))
      }
    },
    {
      id: 'tools:find-replace',
      title: 'Find & Replace',
      description: 'Search and replace text in document',
      icon: <Search className="w-4 h-4" />,
      shortcut: 'Cmd+F',
      category: 'tools',
      action: () => {
        window.dispatchEvent(new Event('tools:find-replace'))
      }
    },

    // Settings
    {
      id: 'settings:open',
      title: 'Settings',
      description: 'Open application settings',
      icon: <Settings className="w-4 h-4" />,
      category: 'settings',
      action: () => {
        window.dispatchEvent(new Event('settings:open'))
      }
    }
  ]

  const allCommands = [...defaultCommands, ...commands]

  // Filter commands based on search query
  const filteredCommands = allCommands.filter(command => {
    const query = searchQuery.toLowerCase()
    return (
      command.title.toLowerCase().includes(query) ||
      command.description?.toLowerCase().includes(query) ||
      command.category.toLowerCase().includes(query)
    )
  })

  // Sort by relevance and recent usage
  const sortedCommands = filteredCommands.sort((a, b) => {
    const aRecent = recentCommands.includes(a.id)
    const bRecent = recentCommands.includes(b.id)

    if (aRecent && !bRecent) return -1
    if (!aRecent && bRecent) return 1
    return 0
  })

  // Group commands by category
  const groupedCommands = sortedCommands.reduce((groups, command) => {
    if (!groups[command.category]) {
      groups[command.category] = []
    }
    groups[command.category].push(command)
    return groups
  }, {} as Record<string, Command[]>)

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus()
      setSelectedIndex(0)
    }
  }, [isOpen])

  useEffect(() => {
    setSelectedIndex(0)
  }, [searchQuery])

  // Handle keyboard navigation
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (!isOpen) return

    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault()
        setSelectedIndex(prev => (prev + 1) % sortedCommands.length)
        break
      case 'ArrowUp':
        e.preventDefault()
        setSelectedIndex(prev => (prev - 1 + sortedCommands.length) % sortedCommands.length)
        break
      case 'Enter':
        e.preventDefault()
        if (sortedCommands[selectedIndex]) {
          executeCommand(sortedCommands[selectedIndex])
        }
        break
      case 'Escape':
        e.preventDefault()
        onClose()
        break
    }
  }, [isOpen, selectedIndex, sortedCommands, onClose])

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown)
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [handleKeyDown])

  const executeCommand = (command: Command) => {
    // Add to recent commands
    setRecentCommands(prev => {
      const updated = [command.id, ...prev.filter(id => id !== command.id)].slice(0, 10)
      localStorage.setItem('recent-commands', JSON.stringify(updated))
      return updated
    })

    // Execute command action
    command.action()
    onClose()
  }

  // Load recent commands from localStorage
  useEffect(() => {
    const saved = localStorage.getItem('recent-commands')
    if (saved) {
      try {
        setRecentCommands(JSON.parse(saved))
      } catch (error) {
        console.error('Failed to load recent commands:', error)
      }
    }
  }, [])

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'file': return <File className="w-4 h-4" />
      case 'edit': return <Terminal className="w-4 h-4" />
      case 'view': return <Settings className="w-4 h-4" />
      case 'ai': return <Zap className="w-4 h-4" />
      case 'tools': return <Terminal className="w-4 h-4" />
      case 'settings': return <Settings className="w-4 h-4" />
      default: return <Terminal className="w-4 h-4" />
    }
  }

  const getCategoryTitle = (category: string) => {
    switch (category) {
      case 'file': return 'File'
      case 'edit': return 'Edit'
      case 'view': return 'View'
      case 'ai': return 'AI Assistant'
      case 'tools': return 'Tools'
      case 'settings': return 'Settings'
      default: return category
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-start justify-center pt-20 z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl mx-4">
        {/* Search input */}
        <div className="flex items-center gap-3 p-4 border-b border-gray-200 dark:border-gray-700">
          <Search className="w-5 h-5 text-gray-400" />
          <input
            ref={inputRef}
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Type a command or search..."
            className="flex-1 bg-transparent border-none outline-none text-gray-900 dark:text-gray-100 placeholder-gray-500"
          />
          <kbd className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded">ESC</kbd>
        </div>

        {/* Commands list */}
        <div className="max-h-96 overflow-y-auto">
          {Object.entries(groupedCommands).map(([category, commands]) => (
            <div key={category}>
              {/* Category header */}
              <div className="flex items-center gap-2 px-4 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                {getCategoryIcon(category)}
                {getCategoryTitle(category)}
              </div>

              {/* Commands in this category */}
              {commands.map((command, index) => {
                const globalIndex = sortedCommands.indexOf(command)
                const isSelected = globalIndex === selectedIndex
                const isRecent = recentCommands.includes(command.id)

                return (
                  <button
                    key={command.id}
                    onClick={() => executeCommand(command)}
                    className={`w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${
                      isSelected ? 'bg-blue-50 dark:bg-blue-900/20 border-l-2 border-blue-500' : ''
                    }`}
                  >
                    <div className="flex items-center gap-3 flex-1">
                      {command.icon}
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-gray-900 dark:text-gray-100">
                            {command.title}
                          </span>
                          {isRecent && <Clock className="w-3 h-3 text-gray-400" />}
                        </div>
                        {command.description && (
                          <div className="text-sm text-gray-500 dark:text-gray-400">
                            {command.description}
                          </div>
                        )}
                      </div>
                    </div>
                    {command.shortcut && (
                      <kbd className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded">
                        {command.shortcut.replace('Cmd', '⌘')}
                      </kbd>
                    )}
                  </button>
                )
              })}
            </div>
          ))}

          {sortedCommands.length === 0 && (
            <div className="flex flex-col items-center justify-center py-12 text-gray-500 dark:text-gray-400">
              <Search className="w-12 h-12 mb-4 text-gray-300" />
              <p>No commands found</p>
              <p className="text-sm">Try a different search term</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-4 py-2 text-xs text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-4">
            <span>{sortedCommands.length} commands</span>
            {searchQuery && <span>Filtered by "{searchQuery}"</span>}
          </div>
          <div className="flex items-center gap-2">
            <kbd className="px-1 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs">↑↓</kbd>
            <span>navigate</span>
            <kbd className="px-1 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs">↵</kbd>
            <span>execute</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default CommandPalette